package com.cg.design.graphicdesignpattern.flyweight;

import java.util.HashMap;

/**
 * 表示生成和共用BigChar类的实例的类，实现共享实例的功能
 *
 * @program: LeetCode->BigCharFactory
 * @description: 表示生成和共用BigChar类的实例的类，实现共享实例的功能
 * @author: cg
 * @create: 2022-04-03 16:32
 **/
public class BigCharFactory {
    /**
     * 管理已经生成的BigChar的实例
     */
    private final HashMap<Character, BigChar> pool = new HashMap<>();
    /**
     * 单例模式
     */
    private static final BigCharFactory SINGLETON = new BigCharFactory();

    /**
     * 禁止创建实例
     */
    private BigCharFactory() {
    }

    /**
     * 获取唯一实例
     *
     * @return
     */
    public static BigCharFactory getInstance() {
        return SINGLETON;
    }

    /**
     * 生成（共享）BigChar类的实例
     * @param charName
     * @return
     */
    public synchronized BigChar getBigChar(char charName) {
        BigChar bigChar = pool.get(charName);
        if (bigChar == null) {
            bigChar = new BigChar(charName);
            pool.put(charName, bigChar);
        }
        return bigChar;
    }
}
